<template>
	<view>
		<uni-forms :modelValue="formInfo">
			<uni-forms-item label="收货人" required>
				<uni-easyinput v-model="formInfo.username" placeholder="请输入收货人" />
			</uni-forms-item>
			<uni-forms-item label="手机号" required>
				<uni-easyinput v-model="formInfo.tel" placeholder="请输入手机号" />
			</uni-forms-item>
			<uni-forms-item label="地址">
				<uni-data-picker placeholder="请选择地址" popup-title="请选择所在地区" :localdata="dataTree" v-model="formInfo.address"
					@change="onchange" >
				</uni-data-picker>
			</uni-forms-item>
			<view class="">
				<text>是否为默认地址</text>
				<switch @change="onChange" :checked="isDefault" /> 
			</view>
			
		</uni-forms>
		<button @click="submitForm">Submit</button>

	</view>
</template>

<script>
	import {mapMutations} from 'vuex';
	import store from '@/store/index.js';//需要引入store
	export default {
		data() {
			return {
				isDefault: false,
				addressInfo: '',
				formInfo: {
					username: '',
					tel: '',
					address: ''
				},
				dataTree: [{
						text: "山西省",
						value: "1-0",
						children: [{
								text: "太原",
								value: "1-1"
							},
							{
								text: "阳泉",
								value: "1-2"
							},{
								text: "临汾",
								value: "1-3"
							}
						]
					},
					{
						text: "河北",
						value: "2-0",
						children: [{
								text: "石家庄",
								value: "2-1"
							},
							{
								text: "邯郸",
								value: "2-2"
							}
						]
					}
				]
			}
		},
		methods: {
			...mapMutations(['addAdress','editAddress']),
			onchange(e) {
				console.log(e)
				this.addressInfo = e.detail.value.map(item => item.text).join('/')
				
			},
			submitForm() {
				console.log(this.$options,'///',)
				if(this.$mp.query?.id) {
					this.editAddress({
						id: this.$mp.query?.id,
						...this.formInfo,
						addressInfo: this.addressInfo,
						isDefault: this.isDefault
					})
				} else {
					this.addAdress({
						...this.formInfo,
						addressInfo: this.addressInfo,
						isDefault: this.isDefault
					})
				}
				uni.navigateBack(1)
			},
			onChange(e) {
				this.isDefault = e.detail.value;
			}
		},
		onLoad(options) {
			const {addressList} = store.state;
			const {username, tel, address, addressInfo, isDefault} = addressList.find(item => item.id == options.id) || {}
			this.formInfo = {
				username,
				tel,
				address
			}
			this.addressInfo = addressInfo;
			this.isDefault = isDefault;
		}
	}
</script>

<style>

</style>